import {
  fetchNotLogEtfActivity,
  fetchLogInEtfActivity,
  fetchLogInEtSubscribe,
} from "@/api/etf-activity";
import { defineStore } from "pinia";
import isEmpty from "lodash/isEmpty";
import { showToast } from "vant";
import { IEtfActivityType } from "@/types/etf-activity";

export const useEtfActivityStore = defineStore("scrmActivity", {
  state: (): IEtfActivityType => ({
    etfActivityData: {},
    loading: false,
  }),
  actions: {
    async getNotLogEtfActivity() {
      const { fetchResource, result, error } = fetchNotLogEtfActivity;
      await fetchResource({});
      if (result.value?.code === "00000") {
        if (result.value?.detail) {
          console.log(result.value?.detail, "未登录-ETF查询接口");
          this.etfActivityData = result.value?.detail ?? {};
        }
      } else {
        showToast("请求出错：" + (result.value?.message || error.value?.message));
      }
      if (isEmpty(result.value) && isEmpty(error.value)) {
        // closePage();
      }
    },
    async getLogInEtfActivity() {
      const { fetchResource, result, error } = fetchLogInEtfActivity;
      await fetchResource({});
      if (result.value?.code === "00000") {
        if (result.value?.detail) {
          console.log(result.value?.detail, "已登录-ETF查询接口");
          this.etfActivityData = result.value?.detail ?? {};
        }
      } else {
        showToast("请求出错：" + (result.value?.message || error.value?.message));
      }
      if (isEmpty(result.value) && isEmpty(error.value)) {
        // closePage();
      }
    },
    async getLogInEtSubscribe() {
      this.loading = true;
      const { fetchResource, result, error } = fetchLogInEtSubscribe;
      await fetchResource({});
      this.loading = false;
      if (result.value?.code === "00000") {
        if (result.value?.detail?.reserveResult === "1") {
          console.log(result.value?.detail, "ETF数预约接口");
          let serial = "";
          if (result.value?.detail?.reserveSort < 10) {
            serial = "00" + result.value?.detail?.reserveSort;
          } else if (result.value?.detail?.reserveSort < 100) {
            serial = "0" + result.value?.detail?.reserveSort;
          } else {
            serial = "" + result.value?.detail?.reserveSort;
          }
          console.log("serial 预约排序位：", serial);
          localStorage.setItem("reserveSort", JSON.stringify(serial));
          showToast("预约成功！");
        } else {
          showToast("预约失败：" + result.value?.detail?.failedReason);
        }
      } else {
        showToast("请求出错：" + (result.value?.message || error.value?.message));
      }
    },
  },
});
